package com.oceansoft.mobile.weixin.core;

import static org.springframework.web.bind.annotation.RequestMethod.GET;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.alibaba.fastjson.JSONObject;
import com.oceansoft.mobile.common.util.Result;
import com.oceansoft.mobile.weixin.util.SignUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import com.oceansoft.mobile.common.Constant;
import com.oceansoft.mobile.weixin.entity.WX_User;
import com.oceansoft.mobile.weixin.entity.menu.BaseButton;
import com.oceansoft.mobile.weixin.entity.menu.CommonButton;
import com.oceansoft.mobile.weixin.entity.menu.ComplexButton;
import com.oceansoft.mobile.weixin.entity.menu.Menu;
import com.oceansoft.mobile.weixin.entity.menu.ViewButton;
import com.oceansoft.mobile.weixin.service.WechatService;
import com.oceansoft.mobile.weixin.util.MenuUtil;
import com.oceansoft.mobile.weixin.util.WeixinUtil;

@Controller
@RequestMapping("wechart")
public class WeChartController {
    @Resource
    private WechatService wechatService;

    /**
     * http://221.224.33.76/oswechat/wechart/menu_get?mer_id=1056
     *
     * @param session
     * @param mer_id
     * @param model
     * @return
     */
    @RequestMapping(value = "menu_get", method = GET)
    public String getMenu(HttpSession session, @RequestParam(value = "mer_id", required = true) String mer_id, Model model) {
        String token = WeixinUtil.getAccessTokenMer(mer_id);
        String menuXML = MenuUtil.getMenu(token);
//    	String menuXML="{'menu':{'button':[{'name':'主菜单3','sub_button':[{'type':'view','name':'菜单21','url':'http://www.baidu.com','sub_button':[]}]}]}}";

//    	JSONObject jsonObject = JSONObject.fromObject(menuXML);
        return "admin/merchant-add";
    }

    /**
     * 提交菜单，将菜单json串提交给微信服务器
     * 现在数据库中初始化菜单,然后运行这个url可以快速创建菜单http://221.224.33.76/oswechat/wechart/menu_create?mer_id=1056
     *
     * @return
     * @author gaoshang
     */
    @RequestMapping(value = "menu_create", method = GET)
    public boolean createMenu(HttpServletRequest request, @RequestParam(value = "mer_id", required = true) String merchant_id) {
        String openid = wechatService.findWXOpenIdbyMerId(merchant_id);
        List<Map<String, Object>> map1 = wechatService.findFirstMenu(openid);//根据openId查询一级菜单
        List<BaseButton> complexbuttonlist = new ArrayList<BaseButton>();//存放父级和子级菜单的集合
        if (map1 != null && map1.size() > 0) {
            for (int i = 0; i < map1.size(); i++) {
                long first_menu_id = Long.parseLong(map1.get(i).get("sid").toString());
                List<Map<String, Object>> map2 = wechatService.findSecondMenu(first_menu_id);//根据一级菜单id查询相对应的二级菜单
                if (map2 != null && map2.size() > 0) {//如果有二级菜单作处理
                    List<BaseButton> buttonlist = new ArrayList<BaseButton>();//把两种类型的button都放进list中
                    for (int j = 0; j < map2.size(); j++) {
                        if (map2.get(j).get("m_type") != null) {
                            if ((map2.get(j).get("m_type").toString()).equals(Constant.CLICK_TYPE_CLICK)) {
                                CommonButton commonbutton = new CommonButton();
                                commonbutton.setType(map2.get(j).get("m_type").toString());
                                if (map2.get(j).get("M_NAME") != null) {
                                    commonbutton.setName(map2.get(j).get("M_NAME").toString());
                                }
                                if (map2.get(j).get("M_KEY") != null) {
                                    commonbutton.setKey(map2.get(j).get("M_KEY").toString());
                                }
                                buttonlist.add(commonbutton);
                            } else {
                                ViewButton viewbutton = new ViewButton();
                                viewbutton.setType(map2.get(j).get("M_TYPE").toString());
                                if (map2.get(j).get("M_NAME") != null) {
                                    viewbutton.setName(map2.get(j).get("M_NAME").toString());
                                }
                                if (map2.get(j).get("M_URL") != null) {
                                    viewbutton.setUrl(map2.get(j).get("M_URL").toString());
                                }
                                buttonlist.add(viewbutton);
                            }
                        }
                    }
                    //父按钮
                    ComplexButton complexbutton = new ComplexButton();
                    complexbutton.setName(map1.get(i).get("M_NAME").toString());
                    //建一个数组，将list中的对象放进数组中,set方法需要传入数组
                    BaseButton[] basebutton = new BaseButton[buttonlist.size()];
                    for (int p = 0; p < buttonlist.size(); p++) {
                        basebutton[p] = buttonlist.get(p);
                    }
                    complexbutton.setSub_button(basebutton);//一个带二级菜单的一级菜单对象
                    complexbuttonlist.add(complexbutton);
                } else {//如果没有二级菜单做处理
                    if (map1.get(i).get("M_TYPE") != null) {
                        if ((map1.get(i).get("M_TYPE").toString()).equals(Constant.CLICK_TYPE_CLICK)) {
                            CommonButton commonbutton = new CommonButton();
                            commonbutton.setType(map1.get(i).get("M_TYPE").toString());
                            if (map1.get(i).get("M_NAME") != null) {
                                commonbutton.setName(map1.get(i).get("M_NAME").toString());
                            }
                            if (map1.get(i).get("M_KEY") != null) {
                                commonbutton.setKey(map1.get(i).get("M_KEY").toString());
                            }
                            complexbuttonlist.add(commonbutton);
                        } else {
                            ViewButton viewbutton = new ViewButton();
                            viewbutton.setType(map1.get(i).get("M_TYPE").toString());
                            if (map1.get(i).get("M_NAME") != null) {
                                viewbutton.setName(map1.get(i).get("M_NAME").toString());
                            }
                            if (map1.get(i).get("M_URL") != null) {
                                viewbutton.setUrl(map1.get(i).get("M_URL").toString());
                            }
                            complexbuttonlist.add(viewbutton);
                        }
                    }
                }
            }
            Menu menu = new Menu();
            BaseButton[] menubutton = new BaseButton[complexbuttonlist.size()];
            for (int k = 0; k < complexbuttonlist.size(); k++) {
                menubutton[k] = complexbuttonlist.get(k);
            }
            menu.setButton(menubutton);
            String token = WeixinUtil.getAccessTokenMer(merchant_id);
            boolean succ = MenuUtil.createMenu(menu, token);
            return succ;
        }
        return false;
    }

    @RequestMapping(value = "oauth/{state}", method = RequestMethod.GET)
    public void gotoIndexByOauth(HttpServletRequest request, HttpServletResponse response, HttpSession session, @PathVariable("state") String state, Model model) {
        System.out.println("======进入oauth=====");
        String base = WeixinUtil.USERINFO_URL;
        final String APPID = "wx87f88d3094b6a3d3";//乐在苏州（服务号）
        base = base.replace("APPID", APPID).replace("STATE", state);
        try {
            response.sendRedirect(base);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    @RequestMapping(value = "oauth/{page}/{openid}/{mer_id}/{ch_id}", method = RequestMethod.GET)
    public void doOauth(HttpServletRequest request, HttpServletResponse response, @PathVariable("page") String page, @PathVariable("openid") String openid, @PathVariable("mer_id") long mer_id, @PathVariable("ch_id") long ch_id) {
        System.out.println("网页授权回调处理--pre");
        WX_User user = wechatService.getWXUser(openid);
        String url = "";
        if (null != user && StringUtils.hasText(user.getNickname())) {
            url = String.format("/lohas/%1$s/%2$s/%3$s", page, mer_id, ch_id);
            System.out.println("==url=" + url);
            try {
                request.getRequestDispatcher(url).forward(request, response);
            } catch (ServletException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            String base = WeixinUtil.BASE_URL;
            final String APPID = "wxaec9e61bdd3f83cb";//苏州青旅体育中心店的
            base = base.replace("APPID", APPID).replace("PAGE", page).replace("OPENID", openid).replace("MERID", mer_id + "").replace("CHID", ch_id + "");
            try {
                response.sendRedirect(base);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    }

    /**
     * 获取签名
     *
     * @param url
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "location")
    public Result shijianc(@RequestParam("url") String url, HttpServletRequest request) {
        String jsapiTicket = wechatService.getJsapiTicket();
        System.out.println("==========url：========" + url);
        System.out.println("==========jsapiTicket：" + jsapiTicket);
        JSONObject json = SignUtil.getSignature(jsapiTicket, url);
        System.out.println("==========json：" + json.toJSONString());
        Result result = new Result();
        result.setData(json);
        return result;
    }

    /**
     * 获取签名(第二次获取签名（不从缓存中拿）)
     *
     * @param url
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "location_two")
    public Result getQMAgain(@RequestParam("url") String url, HttpServletRequest request) {
        String jsapiTicket = wechatService.getJsapiTicket2();
        System.out.println("==========第二次url：========" + url);
        System.out.println("==========第二次jsapiTicket：" + jsapiTicket);
        JSONObject json = SignUtil.getSignature(jsapiTicket, url);
        System.out.println("==========第二次json：" + json.toJSONString());
        Result result = new Result();
        result.setData(json);
        return result;
    }


}
